package student.aistar.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import student.aistar.layOrder.enums.DelayTypeEnum;
import student.aistar.layOrder.producer.DelayMessageProducer;
import student.aistar.mapper.CartMapper;
import student.aistar.mapper.OrderMapper;
import student.aistar.mapper.UserMapper;
import student.aistar.model.dto.GenerateOrderDTO;
import student.aistar.model.dto.OrderAndOrderDetailDTO;
import student.aistar.model.entity.*;
import student.aistar.service.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @Description:
 * @Auther: zhugefeng
 * @Date:2021/9/27 20:38
 **/
@Service
@Transactional
public class OrderServiceImpl implements IOrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    ICartService cartService;
    @Autowired
    IUserService userService;
    @Autowired
    IIndexService iIndexService;
    @Autowired
    IOrderService orderService;
    @Autowired
    IProductService productService;

    @Resource
    private DelayMessageProducer producer;

    @Override
    public User getUserByName(String username) {
        return orderMapper.findUserByName(username);
    }

    @Override
    public List<Orders> getOrderByUser(Integer userId) {
        return orderMapper.findOrderByUser(userId);
    }

    @Override
    public List<Orderdetail> getOrderDetail(Integer orderId) {

        return orderMapper.findOrderDetail(orderId);
    }

    @Override
    public Orders getOrdersByOrderId(Integer orderId) {
        return orderMapper.findOrdersByOrderId(orderId);
    }

    @Override
    public Address getAddressByAddressId(Integer addressId) {
        return orderMapper.findAddressByAddressId(addressId);
    }

    @Override
    public List<OrderStatus> getAllOrderStatus() {
        return orderMapper.findAllOrderStatus();
    }

    @Override
    public PageInfo<Orders> getOrderByNameStatus(Long orderNumber, Integer orderStatus,Integer userId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);

        List<Orders> ordersList =orderMapper.findOrderByNameStatus(orderNumber,orderStatus,userId);

        PageInfo<Orders> pageInfo = new PageInfo<>(ordersList);

        return pageInfo;
    }

    @Override
    public int delOrderlById(Integer orderId) {
        return orderMapper.delOrderlById(orderId);
    }

    @Transactional
    @Override
    public int insertOrdersComeCart(Orders orders) {
        return orderMapper.insertOrdersComeCart(orders);
    }

    @Transactional
    @Override
    public void insertOrderDetailFormCart(Orderdetail orderdetail) {
        orderMapper.insertOrderDetailFormCart(orderdetail);
    }

    /**
     * 用来产生订单和订单详情的信息, 并且从购物车中删除该商品, 并且页面显示出啦
     * @param paraCartProduct
     * @param indexAddress
     * @param user
     */
    @Transactional
    @Override
    public OrderAndOrderDetailDTO generateOrder(String paraCartProduct, Integer indexAddress, User user) {

        double orderTotalPirce = 0;

        Address address = userService.getCheckAddress(indexAddress);
        String[] paraCartProductArr = paraCartProduct.split(":");
        List<Cart> cartList = new ArrayList<>();
        Double totalPrices = 0.0;

        //设置订单对象, 并将对象插入到订单表
        Orders orders = new Orders();
        String orderNumber = new Date().getTime() + "" + user.getUserId();
        orders.setOrderNumber(Long.valueOf(orderNumber));
        orders.setUserId(user.getUserId());

        //一一删除购物车中商品, 并且得到总价
        for(int i = 0; i < paraCartProductArr.length; i++){
            //放入到list集合中, 前端遍历
            Cart cart = cartService.findUserCheckCart((Integer.valueOf(paraCartProductArr[i])));
            totalPrices += cart.getTotalprice();
            orderTotalPirce += cart.getTotalprice();
            cartList.add(cart);

            //从购物车中删除该商品
            cartService.deleteCartProduct(cart.getCartId());
        }

        orders.setOrderAmount((long) orderTotalPirce);
        orders.setPayAmount((long) orderTotalPirce);
        orders.setAddressId(address.getAddressId());
        orders.setBuyNumber(cartList.size());
        //插入订单
        orderService.insertOrdersComeCart(orders);

        //一个订单有多个订单详情, 设置订单对象并插入订单详情表
        for(int i = 0; i < cartList.size(); i++){
            Orderdetail orderdetail = new Orderdetail();
            orderdetail.setOrderId(orders.getOrderId());
            orderdetail.setProductId(cartList.get(i).getProductId());
            orderdetail.setName(cartList.get(i).getParaName());
            orderdetail.setPicImg(productService.findById(cartList.get(i).getProductId()).getPicImg());
            orderdetail.setProductSpecNumber(1);
            orderdetail.setProductSpecName(cartList.get(i).getParaName());
            orderdetail.setPrice(cartList.get(i).getParaPrice());
            orderdetail.setBuyNumber(cartList.get(i).getNum());
            orderdetail.setProductAmount(cartList.get(i).getTotalprice());
            orderService.insertOrderDetailFormCart(orderdetail);
        }

        List<Orderdetail> orderDetailList = orderMapper.findOrderDetail(orders.getOrderId());
//        Address address = userService.getCheckAddress(orders.getAddressId());
        OrderAndOrderDetailDTO orderAndOrderDetailDTO = new OrderAndOrderDetailDTO();

        orderAndOrderDetailDTO.setAddress(address);
        orderAndOrderDetailDTO.setOrders(orders);
        orderAndOrderDetailDTO.setOrderDetailList(orderDetailList);

        //将订单放入到消息队列, 队列有一分钟的倒计时, 如果该时间内, 未支付, 则订单取消
        producer.send(String.valueOf(orders.getOrderNumber()), Objects.requireNonNull(DelayTypeEnum.getDelayTypeEnum(1)));
        return orderAndOrderDetailDTO;
    }

    /**
     * 点击立即支付时， 把订单信息传回去
     * @param user
     * @param orderId
     * @return
     */
    @Override
    public OrderAndOrderDetailDTO goToBuy(User user, Integer orderId) {
        Orders orders = orderMapper.findOrdersByOrderId(orderId);
        List<Orderdetail> orderDetailList = orderMapper.findOrderDetail(orderId);
        Address address = userService.getCheckAddress(orders.getAddressId());
        OrderAndOrderDetailDTO orderAndOrderDetailDTO = new OrderAndOrderDetailDTO();

        orderAndOrderDetailDTO.setAddress(address);
        orderAndOrderDetailDTO.setOrders(orders);
        orderAndOrderDetailDTO.setOrderDetailList(orderDetailList);

        return orderAndOrderDetailDTO;
    }

    @Override
    public void updateOrdersStatus(Long orderNumber) {
        orderMapper.updateOrdersStatus(orderNumber);
    }

    @Override
    public void updateOrdersStatusDead(Long orderNumber) {
        orderMapper.updateOrdersStatusDead(orderNumber);
    }

    @Override
    public int selectOrdersStatus(Long orderNumber) {
        return orderMapper.selectOrderStatus(orderNumber);
    }


}
